package com.qd.panda.service.hk;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.math.Money;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cdqidi.core.weixinmanager.service.wx.WxaApiService;
import com.cdqidi.core.weixinmanager.util.CallWxUtil;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.DateUtil;
import com.cdqidi.util.ServletUtil;
import com.cdqidi.util.SpringContextHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jfinal.springboot.weixin.annotation.ApiType;
import com.qd.common.panda.config.PandaParkConfigDTO;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.hk.HkArrearsRecordsDataReq;
import com.qd.common.panda.domain.entity.hk.HkParkOrderDTO;
import com.qd.common.panda.domain.entity.hk.HkPaymentInfoReq;
import com.qd.common.panda.domain.entity.hk.mq.HttpMsgData;
import com.qd.common.panda.domain.entity.stroke.PayParamDTO;
import com.qd.common.panda.util.PlateColorUtil;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.domain.wx.WxUserDTO;
import com.qd.hik.dto.HkBaseHttpResp;
import com.qd.hik.dto.charge.HkArrearsRecordsResp;
import com.qd.hik.dto.charge.HkPaymentInfoResp;
import com.qd.hik.service.HkChargeService;
import com.qd.panda.model.HkParkOrder;
import com.qd.panda.model.Plate;
import com.qd.panda.model.UserPlateRelation;
import com.qd.panda.mq.HkMsgProducer;
import com.qd.panda.service.park.CarParkService;
import com.qd.panda.service.plate.PlateService;
import com.qd.panda.service.plate.UserPlateRelationService;
import com.qd.panda.service.stroke.DisplayUtil;
import com.qd.panda.service.stroke.UserStrokeHolderService;
import com.qd.pay.config.PayConstant;
import com.qd.pay.domain.OrderDTO;
import com.qd.pay.service.order.OrderHolderService;
import com.qd.system.service.person.AuthTokenService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sjk
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class HkService {
    private final HkParkOrderService hkParkOrderService;
    private final OrderHolderService orderHolderService;
    private final ObjectMapper objectMapper;
    private final HkMsgProducer hkMsgProducer;
    private final HkChargeService hkChargeService;
    private final UserPlateRelationService userPlateRelationService;
    private final PlateService plateService;
    private final CarParkService carParkService;
    @Resource
    private final PandaParkConfigDTO pandaParkConfig;
    @Resource
    private final AuthTokenService authTokenService;
    @Resource
    private WxaApiService wxaApiService;

    /**
     * 欠费记录
     *
     * @param plateNo 车牌号
     * @return 记录
     */
    @Transactional(readOnly = true)
    public List<HkArrearsRecordsResp> getArrearsRecords(String plateNo) {
        List<String> plateList = new ArrayList<>();
        if (StringUtils.hasLength(plateNo)) {
            plateList.add(plateNo);
        }
        LoginUser loginUser = authTokenService.getLoginUser(ServletUtil.getRequest());
        if (null != loginUser) {
            if (!StringUtils.hasLength(plateNo)) {
                List<UserPlateRelation> list = userPlateRelationService.getUserPlateRelationByUserId(loginUser.getUserId());
                if (list.isEmpty()) {
                    throw new ApiException("当前用户未绑定车牌");
                }
                plateList = list.stream().map(UserPlateRelation::getPlateNumber).collect(Collectors.toList());
            }
        }
        if (plateList.isEmpty()) {
            throw new ApiException("手机号不能为空");
        }
        List<HkArrearsRecordsResp> dataList = null;
        for (String s : plateList) {
            HkBaseHttpResp<List<HkArrearsRecordsResp>> resp = hkChargeService.getArrearsRecords(s, null);
            if (resp.isSuccess()) {
//                List<HkArrearsRecordsResp> data = resp.getData();
//                if (null != data && !data.isEmpty()) {
//                    data.forEach(hk -> hk.setParkName(carParkService.idToDisplay(hk.getParkCode())));
//                    dataList.addAll(data);
//                }
                dataList = resp.getData();
            } else {
                throw new ApiException(Optional.ofNullable(resp.getMsg()).orElse("获取欠费记录异常"));
            }
        }
        if (null == dataList) {
            dataList = Collections.emptyList();
        }
        if (!dataList.isEmpty()) {
            dataList = dataList.stream().sorted(Comparator.comparing(HkArrearsRecordsResp::getArrearsTime).reversed()).collect(Collectors.toList());
        }
        return dataList;
    }


    /**
     * 创建临停订单，线上支付
     *
     * @param req 临停参数
     * @return 支付参数
     */
    @Transactional(rollbackFor = Exception.class)
    public PayParamDTO createOrder(HkPaymentInfoReq req) {
        checkPayment(req);
        String userId = null;
        String phone = null;
        String bid = IdWorker.getIdStr();
        LoginUser loginUser = authTokenService.getLoginUser(ServletUtil.getRequest());
        if (null != loginUser) {
            userId = loginUser.getUserId();
            phone = loginUser.getUser().getAppUserExtend().getMobile();
        }
        HkParkOrderDTO hkParkOrderDTO = createHkParkOrder(req);
        if (StringUtils.hasLength(userId)) {
            hkParkOrderDTO.setUserId(userId);
        }
        if (StringUtils.hasLength(phone)) {
            hkParkOrderDTO.setPhone(phone);
        }
        hkParkOrderDTO.setPayStatus(DisplayUtil.PAY_STATUS_0);
        hkParkOrderDTO.setBid(bid);
        hkParkOrderDTO.setPayMethod(PandaConstant.PAY_METHOD_WX);
        hkParkOrderService.save(hkParkOrderDTO);
        hkParkOrderDTO.freeData();
        if (SpringContextHolder.getActiveProfile().equals(SpringContextHolder.PROFILE_DEV)) {
            return null;
        }
        return createOrder(req.getCode(), PandaConstant.HK_ORDER_TYPE_1, req.getPayMoney(), bid);
    }

    /**
     * 创建临停订单，钱包支付
     *
     * @param req 临停参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(HkPaymentInfoReq req, LoginUser loginUser, String id, BigDecimal walletAmount, BigDecimal walletGiveAmount, LocalDateTime now) {
        checkPayment(req);
        HkParkOrderDTO hkParkOrderDTO = createHkParkOrder(req);
        hkParkOrderDTO.setOrderLogId(id);
        hkParkOrderDTO.setUserId(loginUser.getUserId());
        hkParkOrderDTO.setPhone(loginUser.getUser().getAppUserExtend().getMobile());
        hkParkOrderDTO.setPayStatus(DisplayUtil.PAY_STATUS_1);
        hkParkOrderDTO.setBid(id);
        hkParkOrderDTO.setPayMethod(PandaConstant.PAY_METHOD_WALLET);
        hkParkOrderDTO.setWalletAmount(walletAmount);
        hkParkOrderDTO.setWalletGiveAmount(walletGiveAmount);
        hkParkOrderDTO.setPayTime(now);
        hkParkOrderService.save(hkParkOrderDTO);
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCompletion(int status) {
                if (TransactionSynchronization.STATUS_COMMITTED == status) {
                    log.info("钱包支付，通知海康");
                    sendMq(hkParkOrderService.dtoToModel(hkParkOrderDTO));
                }
                hkParkOrderDTO.freeData();
            }
        });
    }

    private HkParkOrderDTO createHkParkOrder(HkPaymentInfoReq req) {
        HkParkOrderDTO hkParkOrderDTO = new HkParkOrderDTO();
        hkParkOrderDTO.setParkId(req.getParkCode());
        hkParkOrderDTO.setParkName(req.getParkName());
        hkParkOrderDTO.setPlateNumber(req.getPlateNo());
        if (null != req.getPlateColor()) {
            hkParkOrderDTO.setPlateColor(req.getPlateColor());
            hkParkOrderDTO.setVehicleColor(PlateColorUtil.hkToPanda(req.getPlateColor()));
        }
        hkParkOrderDTO.setInUnid(req.getInUnid());
        hkParkOrderDTO.setBillCode(req.getBillCode());
        hkParkOrderDTO.setEnterTime(req.getEnterTime());
        hkParkOrderDTO.setCostTime(req.getCostTime());
        hkParkOrderDTO.setParkPeriodTime(req.getParkPeriodTime());
        hkParkOrderDTO.setTotalCost(req.getTotalCost());
        if (null != req.getDeductMoney()) {
            hkParkOrderDTO.setDeductMoney(req.getDeductMoney());
        }
        hkParkOrderDTO.setPayMoney(req.getPayMoney());
        hkParkOrderDTO.setAddTime(LocalDateTime.now());
        hkParkOrderDTO.setPayTime(hkParkOrderDTO.getPayTime());
        hkParkOrderDTO.setOrderType(PandaConstant.HK_ORDER_TYPE_1);
        return hkParkOrderDTO;
    }

    public void checkPayment(HkPaymentInfoReq req) {
        HkBaseHttpResp<HkPaymentInfoResp> resp = hkChargeService.paymentInfo(req.getPlateNo());
        if (resp.isSuccess()) {
            HkPaymentInfoResp data = resp.getData();
            if (null == data) {
                throw new ApiException("不存在缴费信息");
            }
            Integer payMoney = data.getPayMoney();
            if (null == payMoney || payMoney == 0) {
                throw new ApiException("不存在缴费信息");
            }
            if (!Objects.equals(req.getPayMoney(), payMoney)) {
                throw new ApiException("订单金额已经发生变化,请刷新以后支付");
            }
        } else {
            throw new ApiException(resp.getMsg());
        }
        if (hkParkOrderService.paySuccess(req.getBillCode())) {
            log.error("临停支付,当前订单已经支付成功,订单编号: {}", req.getBillCode());
            throw new ApiException("当前订单已经支付成功，请勿重复支付");
        }
    }


    /**
     * 创建欠费订单
     *
     * @param data 欠费列表
     * @return 支付参数
     */
    @Transactional(rollbackFor = Exception.class)
    public PayParamDTO arrears(HkArrearsRecordsDataReq data) {
        List<HkArrearsRecordsDataReq.HkArrearsRecords> list = data.getData();
        String userId = null;
        String phone = null;
        LocalDateTime now = LocalDateTime.now();
        String bid = IdWorker.getIdStr();
        LoginUser loginUser = authTokenService.getLoginUser(ServletUtil.getRequest());
        if (null != loginUser) {
            userId = loginUser.getUserId();
            phone = loginUser.getUser().getAppUserExtend().getMobile();
        }
        checkOrder(data, list);
        List<HkParkOrder> orderList = new ArrayList<>(list.size());
        Integer all = 0;
        for (HkArrearsRecordsDataReq.HkArrearsRecords req : list) {
            if (hkParkOrderService.paySuccess(req.getBillCode())) {
                log.error("欠费补交,当前订单已经支付成功,订单编号: {}", req.getBillCode());
                throw new ApiException("当前订单已经支付成功，请勿重复支付");
            }
            all += req.getArrearsFee();
            HkParkOrder hkParkOrder = createOrder(req, bid, now);
            if (StringUtils.hasLength(userId)) {
                hkParkOrder.setUserId(userId);
            }
            if (StringUtils.hasLength(phone)) {
                hkParkOrder.setPhone(phone);
            }
            hkParkOrder.setPayStatus(DisplayUtil.PAY_STATUS_0);
            hkParkOrder.setPayMethod(PandaConstant.PAY_METHOD_WX);
            hkParkOrder.setWalletAmount(new BigDecimal("0"));
            hkParkOrder.setWalletGiveAmount(hkParkOrder.getWalletAmount());
            orderList.add(hkParkOrder);
        }
        hkParkOrderService.saveBatch(orderList);
        orderList.clear();
        if (SpringContextHolder.getActiveProfile().equals(SpringContextHolder.PROFILE_DEV)) {
            return null;
        }
        return createOrder(data.getCode(), PandaConstant.HK_ORDER_TYPE_2, all, bid);
    }

    /**
     * 取消支付
     *
     * @param bid 业务ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void payError(String bid) {
        List<HkParkOrder> list = hkParkOrderService.getListByBid(bid);
        if (list.isEmpty()) {
            return;
        }
        List<HkParkOrder> updateList = new ArrayList<>();
        for (HkParkOrder hkParkOrder : list) {
            if (hkParkOrder.getPayStatus().equals(DisplayUtil.PAY_STATUS_0)) {
                hkParkOrder.setPayStatus(DisplayUtil.PAY_STATUS_2);
                updateList.add(hkParkOrder);
            }
        }
        if (!updateList.isEmpty()) {
            hkParkOrderService.updateBatchIds(updateList);
            updateList.clear();
        }
        list.clear();
    }

    /**
     * 更新支付状态，并写入mq
     *
     * @param bid       业务状态
     * @param payStatus 支付状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(String bid, Integer payStatus) {
        List<HkParkOrder> list = hkParkOrderService.getListByBid(bid);
        if (list.isEmpty()) {
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        List<HkParkOrder> updateList = new ArrayList<>();
        List<HkParkOrder> sendList = new ArrayList<>();
        for (HkParkOrder hkParkOrder : list) {
            if (hkParkOrder.getPayStatus().equals(DisplayUtil.PAY_STATUS_0)) {
                hkParkOrder.setPayStatus(payStatus);
                hkParkOrder.setPayTime(now);
                if (payStatus.equals(DisplayUtil.PAY_STATUS_1)) {
                    HkParkOrder newHkParkOrder = new HkParkOrder();
                    BeanUtil.copyProperties(hkParkOrder, newHkParkOrder, false);
                    sendList.add(newHkParkOrder);
                }
                updateList.add(hkParkOrder);
            }
        }
        if (!updateList.isEmpty()) {
            hkParkOrderService.updateBatchIds(updateList);
        }
        if (!sendList.isEmpty()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (TransactionSynchronization.STATUS_COMMITTED == status) {
                        for (HkParkOrder hkParkOrder : sendList) {
                            //写入队列
                            log.info("线上支付，通知海康");
                            sendMq(hkParkOrder);
                        }
                        sendList.clear();
                    }
                }
            });
        }
        updateList.clear();
        list.clear();
    }

    @Transactional(readOnly = true)
    public ObjectNode payDetail(String bid) {
        HkParkOrder hkParkOrder = Optional.ofNullable(hkParkOrderService.getOneByBid(bid)).orElseThrow(() -> new ApiException("业务ID值错误"));
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("thirdPartyOrder", bid);
        objectNode.put("addTime", DateUtil.localDateTimeToStr(hkParkOrder.getAddTime()));
        objectNode.put("payMoney", hkParkOrder.getPayMoney());
        if (hkParkOrder.getOrderType().equals(PandaConstant.HK_ORDER_TYPE_1)) {
            objectNode.put("plateNumber", hkParkOrder.getPlateNumber());
            objectNode.put("parkName", carParkService.idToDisplay(hkParkOrder.getParkId()));
            objectNode.put("parkPeriodTime", hkParkOrder.getParkPeriodTime());
        }
//        objectNode.put("payStatus", hkParkOrder.getPayStatus());
//        objectNode.put("payStatusDisplay", DisplayUtil.getPayStatusDisplay(hkParkOrder.getPayStatus()));
        return objectNode;
    }

    public HkParkOrder createOrder(HkArrearsRecordsDataReq.HkArrearsRecords req, String bid, LocalDateTime now) {
        HkParkOrder hkParkOrder = new HkParkOrder();
        hkParkOrder.setParkId(req.getParkCode());
        hkParkOrder.setParkName(req.getParkName());
        hkParkOrder.setPlateNumber(req.getPlateNo());
        if (null != req.getPlateColor()) {
            hkParkOrder.setPlateColor(req.getPlateColor());
            hkParkOrder.setVehicleColor(PlateColorUtil.hkToPanda(req.getPlateColor()));
        }
        hkParkOrder.setInUnid(req.getInUnid());
        hkParkOrder.setBillCode(req.getBillCode());
        hkParkOrder.setTotalCost(req.getTotalFee());
        hkParkOrder.setPayMoney(req.getArrearsFee());
        hkParkOrder.setAddTime(now);
        hkParkOrder.setPayTime(now);
        hkParkOrder.setBerthCode(req.getBerthCode());
        hkParkOrder.setArrearsTime(req.getArrearsTime());
        hkParkOrder.setBid(bid);
        hkParkOrder.setOrderType(PandaConstant.HK_ORDER_TYPE_2);
        return hkParkOrder;
    }


    private PayParamDTO createOrder(String code, Integer orderType, Integer payMoney, String bid) {
        if (!StringUtils.hasLength(pandaParkConfig.getParkPartner())) {
            throw new ApiException("配置停车支付主商户");
        }
        if (!StringUtils.hasLength(pandaParkConfig.getParkSubPartner())) {
            throw new ApiException("配置停车支付子商户");
        }
        LoginUser loginUser = authTokenService.getLoginUser(ServletUtil.getRequest());
        OrderDTO orderDto = new OrderDTO();
        orderDto.setThirdPartyOrder(bid).setPayAmount(centToYuan(payMoney)).setNotifyUrl(pandaParkConfig.getDomain() + "/gy-panda-park/app/userStroke/notify/payAfter").setType(PayConstant.ORDER_TYPE_2).setAppId(pandaParkConfig.getDefaultMiniProgramAppId()).setPartner(pandaParkConfig.getParkPartner()).setSubPartner(pandaParkConfig.getParkSubPartner());
        if (null != loginUser) {
            orderDto.setPersonId(loginUser.getUserId());
        }
        WxUserDTO wxUserDTO = getWxUserDTO(pandaParkConfig.getDefaultMiniProgramAppId(), code);
        if (null != wxUserDTO) {
            orderDto.setOpenid(wxUserDTO.getOpenid());
        }
        log.info("bid: {},金额: {}", bid, orderDto.getPayAmount());
        ObjectNode attachObjectNode = objectMapper.createObjectNode();
        if (orderType.equals(PandaConstant.HK_ORDER_TYPE_1)) {
            orderDto.setBody("停车场停车缴费").setSubject("临停缴费");
        }
        if (orderType.equals(PandaConstant.HK_ORDER_TYPE_2)) {
            orderDto.setBody("停车场停车缴费").setSubject("欠费补交");
        }
        attachObjectNode.put("orderType", DisplayUtil.ORDER_TYPE_7);
        orderDto.setAttach(attachObjectNode);
        ObjectNode child = objectMapper.createObjectNode();
        ObjectNode wxLite = objectMapper.createObjectNode();
        wxLite.put(UserStrokeHolderService.AMOUNT, orderDto.getPayAmount().doubleValue());
        wxLite.put("sub_appid", pandaParkConfig.getDefaultMiniProgramAppId());
        if (null != wxUserDTO) {
            wxLite.put("sub_openid", wxUserDTO.getOpenid());
        }
        child.set("wx_lite", objectMapper.createArrayNode().add(wxLite));
        orderDto.setChannelDetails(child);

        Map<String, String> params = orderHolderService.createOrder(orderDto);
        if (params.isEmpty()) {
            throw new ApiException("获取支付参数异常");
        }
        PayParamDTO payParamDTO = new PayParamDTO();
        payParamDTO.setAppId(pandaParkConfig.getDefaultMiniProgramAppId()).setNonceStr(params.get("nonceStr")).setPrepayId(params.get("package")).setPaySign(params.get("paySign")).setSignType("MD5").setTimeStamp(params.get("timeStamp")).setThirdPartyOrder(bid);
        payParamDTO.setPayAmount(orderDto.getPayAmount().stripTrailingZeros().toPlainString());
        return payParamDTO;
    }

    private BigDecimal centToYuan(Integer amount) {
        Money money = new Money(0, amount);
        return money.getAmount();
    }

    @Transactional(readOnly = true)
    public void syncToHk(HkParkOrderDTO dto) {
        dto.setPayStatus(DisplayUtil.PAY_STATUS_1);
        List<HkParkOrder> list = hkParkOrderService.getList(dto);
        if (!list.isEmpty()) {
            for (HkParkOrder hkParkOrder : list) {
                sendMq(hkParkOrder);
            }
            list.clear();
        }
    }

    @SneakyThrows
    public void sendMq(HkParkOrder hkParkOrder) {
        HttpMsgData<HkParkOrder> httpMsgData = new HttpMsgData<>();
        httpMsgData.setRetryCount(1);
        httpMsgData.setReqData(hkParkOrder);
        hkMsgProducer.sender(objectMapper.writeValueAsString(httpMsgData));
        httpMsgData.freeData();
    }

    private WxUserDTO getWxUserDTO(String appId, String code) {
        final WxUserDTO wxUser = CallWxUtil.callInterface(appId, ApiType.WXA, () -> {
            final ApiResultWrapper<Object> result = wxaApiService.getWxaOpenId(code);
            if (result.isSuccess()) {
                Object data = result.getData();
                if (data instanceof Map) {
                    Map<?, ?> map = (Map<?, ?>) result.getData();
                    final Object openid = map.get("openid");
                    final Object unionId = map.get("unionid");
                    WxUserDTO dto = new WxUserDTO();
                    dto.setAppId(appId);
                    if (null != unionId) {
                        dto.setUnionId(String.valueOf(unionId));
                    }
                    dto.setOpenid(String.valueOf(openid));
                    dto.setAppId(appId);
                    return dto;
                }

            }
            throw new ApiException("请求微信获得openId接口异常: " + result.getMsg());
        });
        return Optional.ofNullable(wxUser).orElseThrow(() -> new ApiException("获取用户信息为空"));
    }

    public void checkOrder(HkArrearsRecordsDataReq data, List<HkArrearsRecordsDataReq.HkArrearsRecords> list) {
        Set<String> plateNos = list.stream().map(HkArrearsRecordsDataReq.HkArrearsRecords::getPlateNo).collect(Collectors.toSet());
        Set<String> order = new HashSet<>(list.size());
        for (String plateNo : plateNos) {
            HkBaseHttpResp<List<HkArrearsRecordsResp>> resp = hkChargeService.getArrearsRecords(plateNo, null);
            if (resp.isSuccess()) {
                if (null != resp.getData() && !resp.getData().isEmpty()) {
                    order.addAll(resp.getData().stream().map(HkArrearsRecordsResp::getBillCode).collect(Collectors.toSet()));
                }
            } else {
                throw new ApiException("查询欠费记录失败： " + Optional.ofNullable(resp.getMsg()).orElse(""));
            }
        }
        Set<String> billCodeSet = data.getData().stream().map(HkArrearsRecordsDataReq.HkArrearsRecords::getBillCode).collect(Collectors.toSet());
        for (String billCode : billCodeSet) {
            if (!order.contains(billCode)) {
                throw new ApiException("当前订单无需支付:[" + billCode + "]");
            }
        }
    }

    @Transactional(readOnly = true)
    public List<HkPaymentInfoResp> parkOrdersParking(String plateNo) {
        List<UserPlateRelation> list;
        if (StringUtils.hasLength(plateNo)) {
            list = new ArrayList<>(1);
            list.add(new UserPlateRelation().setPlateNumber(plateNo));
        } else {
            LoginUser loginUser = authTokenService.getLoginUser(ServletUtil.getRequest());
            if (null == loginUser) {
                if (!StringUtils.hasLength(plateNo)) {
//                    throw new ApiException("车牌号码不能为空");
                    return new ArrayList<>();
                }
                list = new ArrayList<>(1);
                list.add(new UserPlateRelation().setPlateNumber(plateNo));
            } else {
                final String userId = loginUser.getUserId();
                list = userPlateRelationService.getUserPlateRelationByUserId(userId);
                if (list.isEmpty()) {
                    throw new ApiException(40400, "未绑定车牌号");
                }
            }
        }
        List<HkPaymentInfoResp> respList = new ArrayList<>();
        for (UserPlateRelation userPlateRelation : list) {
//            HkParkOrderParkingReq req = new HkParkOrderParkingReq();
//            req.setPlateNo(userPlateRelation.getPlateNumber());
//            final HkBaseHttpResp<HkParkOrderParkingResp> resp = hkChargeService.parkOrdersParking(req);
//            if (resp.isSuccess()) {
//                respList.add(resp.getData());
//            } else {
//                throw new ApiException(resp.getMsg());
//            }
//            req.freeData();
            HkBaseHttpResp<HkPaymentInfoResp> resp = hkChargeService.paymentInfo(userPlateRelation.getPlateNumber());
            if (resp.isSuccess()) {
                if (null != resp.getData()) {
                    if (null == resp.getData().getPlateColor()) {
                        Plate plate = plateService.getById(userPlateRelation.getPlateNumber());
                        if (null != plate) {
                            resp.getData().setPlateColor(plate.getVehicleColor());
                        }
                    }
                    respList.add(resp.getData());
                }
            } else {
                if (StringUtils.hasLength(resp.getMsg())) {
                    if (!resp.getMsg().contains("找不到停车记录")) {
                        throw new ApiException(resp.getMsg());
                    }
                } else {
                    throw new ApiException("停车账单查询异常");
                }
            }
        }
        return respList;
    }
}